package com.nowcoder.community.controller;

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: shuhuang
 * @description:
 * @Date: 2022/10/2 22:22
 * @Version java version 1.8
 */
@Controller
public class HomeController {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;

    @GetMapping(path = "/index")
    public String getIndexPage(Model model, Page page,
                               @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index?orderMode=" + orderMode);
        List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (discussPosts != null) {
            for (DiscussPost lists : discussPosts) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", lists);
                User user = userService.findUserById(lists.getUserId());
                map.put("user", user);

                long likeCount = likeService.findEntityLikeCount(ConstantUtil.ENTITY_TYPE_POST, lists.getId());
                map.put("likeCount", likeCount);

                mapList.add(map);
            }
        }
        model.addAttribute("discussPosts", mapList);
        model.addAttribute("orderMode", orderMode);
        return "/index";
    }

    @GetMapping("/denied")
    public String getDeniedPage() {
        return "/error/404";
    }

}
